<template>
  <div>
    <el-select v-model="projectValue" filterable placeholder="选择项目" @change="fetchProject" style="width: 400px; margin-top: 10px;margin-bottom: 10px;margin-left: 20px">
    <el-option
      v-for="item in projectoptions"
      :key="item.PUID"
      :label="item.project_name"
      :value="item.project_id"
    />
  </el-select>

  </div>
  <div class="demo-collapse">
    <el-collapse v-model="activeNames" @change="handleChange">
      <el-collapse-item title="Consistency" name="1">
        <template #title>
          <span style="font-weight: bold;font-size: large;">项目基本信息</span>
        </template>
        <el-row :gutter="20">
        <el-col :span="16"><div class="grid-content"/>
          <el-card class="box-card" style="height: 350px;">
            <el-descriptions :data="projectDetail" title="项目信息">
            <el-descriptions-item label="项目编码：">{{projectDetail.project_id}}</el-descriptions-item>
            <el-descriptions-item label="项目名称：">{{projectDetail.project_name}}</el-descriptions-item>
            <el-descriptions-item label="项目经理：">{{projectDetail.user_name}}</el-descriptions-item>
            <el-descriptions-item label="项目类型：">{{projectDetail.project_type}}</el-descriptions-item>
            <el-descriptions-item label="项目子类型：">{{projectDetail.project_class}}</el-descriptions-item>
            <el-descriptions-item label="业务负责人：">{{projectDetail.business_manager}}</el-descriptions-item>
            <!-- <el-descriptions-item label="客户负责人:">靓仔吴</el-descriptions-item> -->
            <el-descriptions-item label="产品类型:">{{projectDetail.product_type}}</el-descriptions-item>
            <el-descriptions-item label="产品规则:">{{projectDetail.product_specification}}</el-descriptions-item>
            <el-descriptions-item label="产品特性:">{{projectDetail.product_feature}}</el-descriptions-item>
            <el-descriptions-item label="工艺特性:">{{projectDetail.process_feature}}</el-descriptions-item>
            <el-descriptions-item label="主材料:">{{projectDetail.main_material}}</el-descriptions-item>
            <el-descriptions-item label="功率:">{{projectDetail.product_power}}</el-descriptions-item>
            <el-descriptions-item label="客户图纸编码:">{{projectDetail.customer_drawing_num}}</el-descriptions-item>
            <el-descriptions-item label="主机厂/车型:">{{projectDetail.customer_info}}</el-descriptions-item>
            <el-descriptions-item label="是否新能源:"><el-tag size="small">{{projectDetail.newengry_or_not}}</el-tag></el-descriptions-item>
            <el-descriptions-item label="是否定点:"><el-tag size="small">{{projectDetail.fixed_or_not}}</el-tag></el-descriptions-item>
            <el-descriptions-item label="是否重点项目:">
              <el-tag size="small">{{projectDetail.important_or_not}}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="项目区域:">{{projectDetail.project_area}}</el-descriptions-item>
            <el-descriptions-item label="应用领域:">{{projectDetail.product_use}}</el-descriptions-item>
            <el-descriptions-item label="项目描述:">
             {{projectDetail. project_desc}}
          </el-descriptions-item>
          </el-descriptions>
          </el-card>
        </el-col>
        <el-col :span="8"><div class="grid-content"></div>
          <el-card class="box-card">
       <template #header>
      <div class="card-header">
        <span style="font-weight: bold; font-size: large;" >项目近期目标</span>
      </div>
    </template>
    <el-table :data="MBtableData" height="250" style="width: 100%"  :default-sort="{ prop: 'target_date', order: 'descending' }">
    <el-table-column prop="target_date" label="目标日期"  />
    <el-table-column prop="target_name" label="近期目标"  />
    <el-table-column prop="target_status" label="状态" sortable />
    <el-table-column prop="target_desc" label="描述" />
  </el-table>
  </el-card>
        </el-col>
      </el-row>
      </el-collapse-item>
      <el-collapse-item title="Feedback" name="2">
        <template #title>
          <span style="font-weight: bold;font-size: large;">项目里程碑信息</span>
        </template>
      <div class="table-container">
      <table class="styled-table">
        <tbody>
      <tr class="milestone-row">
        <td>里程碑</td>
        <td v-for="lcb in lcbData" :key="lcb" class="cell">{{ lcb.task_name }}</td>
      </tr>
      <tr>
        <td>计划时间</td>
        <td v-for="lcb in lcbData" :key="lcb" class="cell">{{ lcb.start_date }}</td>
      </tr>
      <tr>
        <td>实际时间</td>
        <td v-for="lcb in lcbData" :key="lcb" class="cell">{{ lcb.act_start_date }}</td>
      </tr>
    </tbody>
  </table>
       </div>
      </el-collapse-item>
      <el-collapse-item title="Efficiency" name="3">
        <template #title>
          <span style="font-weight: bold;font-size: large;">项目任务统计</span>
        </template>
        <el-card>
        <div>
          <el-row>
          <el-col :span="6">
            <el-statistic :value="taskStatistic.done">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  已完成任务数：
                </div>
              </template>
              <template #suffix>/{{taskStatistic.sum}}</template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic title="进行中任务数：" :value="taskStatistic.inProgress" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="延期未完成：" :value="taskStatistic.extension">
              <template #suffix>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic title="未开始任务数：" :value="taskStatistic.nostart">
              <template #suffix>
              </template>
            </el-statistic>
          </el-col>
        </el-row>
              </div>
            </el-card>
      <el-row :gutter="20">
          <el-col :span="16">
            <el-card class="box-card">
       <template #header>
      <div class="card-header">
        <span style="font-weight: bold; font-size: large;">项目计划延迟任务清单</span>
      </div>
       </template>
       <div>
        <el-table :data="taskTableData" :default-sort="{ prop: 'start_date', order: 'descending' }" height="200" style="width: 100%" :header-cell-style="{'background': '#0077a1 !important','color': '#ffffff'}">
        <el-table-column prop="task_name" label="任务名称"  />
        <el-table-column prop="user_name" label="负责人"  />
        <el-table-column prop="start_date" label="计划开始时间" sortable/>
        <el-table-column prop="finish_date" label="计划完成时间" sortable />
        <el-table-column prop="act_start_date" label="实际开始时间" sortable/>
        <el-table-column prop="act_finish_date" label="实际完成时间" sortable/>
      </el-table>
       </div>

  </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="box-card">
       <template #header>
      <div class="card-header">
        <span style="font-weight: bold; font-size: large;">项目成员绩效</span>
      </div>
       </template>
       <div>
        <el-table :data="JxtableData"  height="200" style="width: 100%" :header-cell-style="{'background': '#0077a1 !important','color': '#ffffff'}">
          <el-table-column prop="userName" label="项目成员">
          <template #default="{ row }">
            {{ row.userName }}
            <span v-if="row.isMM === 1">
            <el-tag class="tag small-tag" size="small">PM</el-tag>
           </span>
      </template>
    </el-table-column>
        <el-table-column prop="perfor" label="绩效"  />
      </el-table>
       </div>

  </el-card>
          </el-col>
      </el-row>
      </el-collapse-item>
      <el-collapse-item title="Controllability" name="4">
        <template #title>
          <span style="font-weight: bold;font-size: large;">项目遗留问题统计</span>
        </template>
        <div>
          <el-row>
         <el-col :span="8">
            <!-- <el-statistic title="问题总数：" :value="110"/> -->
            <div><span style="font-weight: bold;font-size: large;">
              问题总数：
              <el-tag class="ml-2" type="danger">{{ QtableData.length }}</el-tag></span></div>
            <div id="Qchart" style="width: 100%; height: 100%;"></div>
        </el-col>
        <el-col :span="16">
          <el-table :data="QtableData"  height="250" :default-sort="{ prop: 'ir_level', order: 'descending' }" style="width: 100%" :header-cell-style="{'background': '#0077a1 !important','color': '#ffffff'}">
        <el-table-column prop="ir_desc" label="问题描述"   fixed/>
        <el-table-column prop="status" label="问题状态" sortable />
        <el-table-column prop="ir_level" label="问题优先级" sortable/>
        <el-table-column prop="project_stage" label="问题所属阶段" />
        <el-table-column prop="responesor" label="问题责任人"  fixed/>
        <el-table-column prop="plan_closedate" label="计划关闭时间"/>
        <el-table-column prop="analysis" label="问题分析" />
        <el-table-column prop="short_solution" label="短期措施" />
        <el-table-column prop="long_solution" label="长期措施" />
      </el-table>
        </el-col>
        </el-row>
        </div>
      </el-collapse-item>
      <el-collapse-item title="Controllability" name="5">
        <template #title>
          <span style="font-weight: bold;font-size: large;">项目风险项统计</span>
        </template>
        <div>
          <el-row>
         <el-col :span="8">
            <!-- <el-statistic title="问题总数：" :value="110"/> -->
            <div><span style="font-weight: bold;font-size: large;">
              风险总数：
              <el-tag class="ml-2" type="danger">{{FtableData.length}}</el-tag></span></div>
            <div id="Fchart" style="width: 100%; height: 100%;"></div>
        </el-col>
        <el-col :span="16">
          <el-table :data="FtableData"  height="250" :default-sort="{ prop: 'risk_level', order: 'descending' }" style="width: 100%" :header-cell-style="{'background': '#0077a1 !important','color': '#ffffff'}">
        <el-table-column prop="risk_name" label="风险要素"  />
        <el-table-column prop="risk_influence" label="风险影响" />
        <el-table-column prop="risk_level" label="风险等级" sortable/>
        <el-table-column prop="solution" label="预防和补救措施" />
        <el-table-column prop="responesor" label="风险责任人" />
        <el-table-column prop="plan_closedate" label="预计关闭时间" sortable/>
      </el-table>
        </el-col>
        </el-row>
        </div>
      </el-collapse-item>
      <el-collapse-item title="Controllability" name="6">
        <template #title>
          <span style="font-weight: bold;font-size: large;">项目资源负荷</span>
        </template>
        <div>
        <el-table :data="resTableData" :border="parentBorder" style="width: 100%" @expand-change="handleExpandChange">
        <el-table-column type="expand">
          <template #default="props">
            <div>
              <h3>指定资源明细：</h3>
              <el-table :data="props.row.taskList" :border="childBorder">
                <el-table-column label="任务名称" prop="task_name" />
                <el-table-column label="所属项目" prop="project_name" />
                <!-- <el-table-column label="任务描述" prop="city" /> -->
                <el-table-column label="任务类型" prop="task_type" />
                <el-table-column label="任务状态" prop="task_status" sortable>
                  <template v-slot="scope">
                    <div :style="{'background-color': getBackgroundColor(scope.row.task_status)}">
                      {{ scope.row.task_status }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="完成百分比" prop="complete_percent" :formatter="formatPercent"/>
                <el-table-column label="计划开始时间" prop="start_date" sortable/>
                <el-table-column label="计划完成时间" prop="finish_date" />
                <el-table-column label="计划工作量" prop="duration" />
              </el-table>
            </div>
      </template>
    </el-table-column>
    <el-table-column label="资源" prop="username" />
    <el-table-column v-for="day in nextWeekDays" :key="day" :label="getColumnLabel(day)" :prop="day">
      <template v-slot="scope">
      <span>{{ scope.row.workLoad[getDateFormat(day)] }}</span>
    </template>
    </el-table-column>
  </el-table>
        </div>
      </el-collapse-item>

    </el-collapse>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import { BASE_URL } from '@/api/project'
const activeNames = ref(['1'])
activeNames.value = ['1', '2', '3', '4', '5', '6']
const handleChange = (val) => {
  console.log(val)
}
const route = useRoute()
const lcbTime = ref([''])
lcbTime.value = ['计划时间', '实际时间']
const parentBorder = ref(false)
const childBorder = ref(false)
const projectValue = ref('')
const projectDetail = ref('')
const projectoptions = ref([])
const taskStatistic = ref('')
const MBtableData = ref([])
const JxtableData = ref([])

function getProjectTarget () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getProjectTargetList?projectId=${projectId}`)
    .then(response => {
      MBtableData.value = response.data // 将获取到的数据赋值
    })
    .catch(error => {
      console.error(error)
    })
}
function gettaskStatistic () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getTaskStatistic?projectId=${projectId}`)
    .then(response => {
      taskStatistic.value = response.data // 将获取到的数据赋值
    })
    .catch(error => {
      console.error(error)
    })
}
const nextWeekDays = ref([])

function getDateFormat (day) {
  const today = new Date()
  const date = new Date(today.getTime() + nextWeekDays.value.indexOf(day) * 24 * 60 * 60 * 1000)
  const formattedDate = formatDate(date)
  return `${formattedDate}`
}
function getColumnLabel (day) {
  const today = new Date()
  const date = new Date(today.getTime() + nextWeekDays.value.indexOf(day) * 24 * 60 * 60 * 1000)
  const formattedDate = formatDate(date)
  const dayOfWeek = getDayOfWeek(date)
  return `${formattedDate}\n${dayOfWeek}`
}

// 计算属性
const computedNextWeekDays = () => {
  const days = []
  const today = new Date()
  for (let i = 0; i < 14; i++) {
    const date = new Date(today.getTime() + i * 24 * 60 * 60 * 1000)
    // const dayOfWeek = date.toLocaleDateString('en-US', { weekday: 'long' })
    days.push(date)
  }
  return days
}
// 获取日期的星期几
function getDayOfWeek (date) {
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const dayIndex = date.getDay()
  return weekdays[dayIndex]
}
// 格式化日期为 "YYYY-MM-DD" 格式
function formatDate (date) {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}
nextWeekDays.value = computedNextWeekDays()
const lcbData = ref([])

const taskTableData = ref([])
const FtableData = ref([])
const FstData = ref([])
const QstData = ref([])
const QtableData = ref([])
const resTableData = ref([])

function getBackgroundColor (taskStatus) {
  if (taskStatus === '完成') {
    return 'lightgreen'
  } else {
    return ''
  }
}

function formatPercent (row, column) {
  const value = row[column.property]
  if (value !== null && value !== undefined) {
    const formattedValue = parseFloat(value).toFixed(2)
    return `${formattedValue}%`
  }
  return '0%'
}

function handleExpandChange (expandRows) {
  console.log('展开行发生变化:', expandRows)
}
function renderFChart () {
  const FchartDom = document.getElementById('Fchart')
  const Fchart = echarts.init(FchartDom)
  const Foption = {
    // title: {
    //   text: '项目未关闭问题统计图',
    //   left: 'center'
    // },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      name: '项目风险统计',
      type: 'pie',
      radius: '80%',
      data: FstData.value

    }]
  }
  Fchart.setOption(Foption)
}
function renderQChart () {
  const QchartDom = document.getElementById('Qchart')
  const Qchart = echarts.init(QchartDom)
  const Qoption = {
    // title: {
    //   text: '项目未关闭问题统计图',
    //   left: 'center'
    // },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      name: '项目问题统计',
      type: 'pie',
      radius: '80%',
      data: QstData.value

    }]
  }
  Qchart.setOption(Qoption)
}
function getMilestones () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getProjectMilestoneList?projectId=${projectId}`)
    .then(response => {
      lcbData.value = response.data // 将获取到的数据赋值
    })
    .catch(error => {
      console.error(error)
    })
}
function getRiskStatistic () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getRiskStatistic?projectId=${projectId}`)
    .then(response => {
      FstData.value = response.data // 将获取到的数据赋值
      renderFChart() // 渲染
    })
    .catch(error => {
      console.error(error)
    })
}
function getJxTabale () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getJX?projectId=${projectId}`)
    .then(response => {
      JxtableData.value = response.data
    })
    .catch(error => {
      console.error(error)
    })
}

function getIssuesStatistic () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getIssuesStatistic?projectId=${projectId}`)
    .then(response => {
      QstData.value = response.data // 将获取到的数据赋值
      renderQChart() // 渲染
    })
    .catch(error => {
      console.error(error)
    })
}
function getIssuesList () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getIssuesList?projectId=${projectId}`)
    .then(response => {
      QtableData.value = response.data // 将获取到的数据赋值
      console.log('问题列表：' + QtableData.value.length)
    })
    .catch(error => {
      console.error(error)
    })
}
function getRisks () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getRiskList?projectId=${projectId}`)
    .then(response => {
      FtableData.value = response.data // 将获取到的数据赋值
      console.log('风险列表：' + FtableData.value.length)
    })
    .catch(error => {
      console.error(error)
    })
}
function getTasks () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getDelayTasks?projectId=${projectId}`)
    .then(response => {
      taskTableData.value = response.data // 将获取到的数据赋值
      console.log('任务列表：' + taskTableData.value.length)
    })
    .catch(error => {
      console.error(error)
    })
}
function fetchProjects () {
  axios.get(BASE_URL + '/getProjectSelector')
    .then(response => {
      projectoptions.value = response.data // 将获取到的数据赋值给 projectoptions 数组
    })
    .catch(error => {
      console.error(error)
    })
}
function getMembers () {
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getMembers?projectId=${projectId}`).then(response => {
    resTableData.value = response.data
  }).catch(error => {
    console.error(error)
  })
}
function fetchProject () {
  // 根据选择的项目值进行相应的处理
  console.log('Selected project:', projectValue.value)
  const projectId = projectValue.value // 使用选择的项目值作为参数
  axios.get(BASE_URL + `/getProjectDetail?projectId=${projectId}`)
    .then(response => {
      projectDetail.value = response.data // 将获取到的数据赋值给 projectDetail 对象
    })
    .catch(error => {
      console.error(error)
    })
  getTasks()
  gettaskStatistic()
  getRisks()
  getRiskStatistic()
  getIssuesList()
  getIssuesStatistic()
  getMilestones()
  getMembers()
  getProjectTarget()
  getJxTabale()
}

onMounted(() => {
  const queryId = route.query.id
  if (queryId) {
    projectValue.value = queryId
    fetchProject()
    getTasks()
    gettaskStatistic()
    getRisks()
    getRiskStatistic()
    getIssuesList()
    getIssuesStatistic()
    getMilestones()
    getMembers()
    getProjectTarget()
    getJxTabale()
  }
  fetchProjects() // 在组件挂载后调用获取数据的方法
})
</script>

<style scoped>
.fixed-row {
  background-color: #f5f7fa; /* 自定义颜色或样式 */
  font-weight: bold; /* 自定义样式 */
}
.table-container{
  width:  100%;
}
.custom-column {
  font-weight: bold;
}
.styled-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  text-align: center;
  font-weight: bold;
}

.styled-table td {
  border: 1px solid #ddd;
  padding: 8px;
}

.styled-table tr:nth-child(even) {
  background-color: #f2f2f2;
}

.styled-table tr:hover {
  background-color: #e5e5e5;
}

.styled-table td:first-child {
  font-weight: bold;
}
.milestone-row {
  /* 在这里添加你的自定义样式 */
  background: #0077a1 !important;
  color: #ffffff;
}
.small-tag {
  font-size: 8px;
  padding: 2px 6px;
  line-height: 1;
}
</style>
